﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;

namespace JTTD.Common.Helper
{
    /// <summary>
    /// xml工具类
    /// </summary>
    public static  class XmlHelper
    {
        /// <summary>
        /// 读取xml文档
        /// </summary>
        /// <param name="xmlFileName"></param>
        /// <returns></returns>
        public  static XDocument  LoadXmlConfig(string xmlFileName)
        {
            string url = Directory.GetCurrentDirectory() + @"/"+xmlFileName;
            if(!File.Exists(url))
            {
                throw new System.Exception($"{xmlFileName}文件不存在");
            }
            XDocument xDocument = XDocument.Load(url);
            return xDocument;
        }

        /// <summary>
        /// 获取具体节点下面的子节点
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xElement"></param>
        /// <param name="nodeName"></param>
        /// <returns></returns>
        public static List<LoadXmlResult<T>> GetChildNode<T>(XElement xElement) where T: new()
        {
            List<LoadXmlResult<T>> list = new List<LoadXmlResult<T>>();
            PropertyInfo[] propertyInfos = typeof(T).GetProperties();
            if(xElement .Elements().Any())
            {
                foreach (var item in xElement.Elements())
                {
                    LoadXmlResult<T> result = new LoadXmlResult<T>();
                    T model = new T();
                    foreach (var property in propertyInfos)
                    {
                        XAttribute xAttribute= item.Attribute(property.Name);
                        if(xAttribute!=null)
                        {
                            var value = Convert.ChangeType(xAttribute.Value, property.PropertyType);
                            property.SetValue(model, value);
                        }
                       
                    }
                    result.Node = model;
                    if(item.Elements().Any())
                    {
                        result.ChildNodes= GetChildNode<T>(item);
                    }
                    list.Add(result);
                }
            }
            return list;
        }
    }

    /// <summary>
    /// 读取xml节点通用类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class LoadXmlResult<T> where T:new ()
    {
        /// <summary>
        /// 当前节点
        /// </summary>
        public T Node { get; set; }
        /// <summary>
        /// 子节点
        /// </summary>
        public List<LoadXmlResult<T>> ChildNodes { get; set; }
    }
}
